import 'package:flutter/material.dart';

import 'package:scrawl/third_part/bloc/bloc.dart';

import '../bloc/edit_scrawl_bloc.dart';
import 'gesture_zoom_box.dart';
import 'scrawl_panel_widget.dart';
import 'scrawl_preview_widget.dart';
import 'scrawl_widget.dart';

class ScrawlPage extends StatelessWidget {
  const ScrawlPage({Key key}) : super(key: key);

  // pic.jpg: 720 / 1280
  // l.jpg: 800 / 534
  // s.jpg: 200 / 300
  final imageAspectRatio = 800 / 534;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => EditScrawlBloc(context),
      child: Builder(
        builder: (BuildContext context) => _buildPage(context),
      ),
    );
  }

  Widget _buildPage(BuildContext context) {
    // ignore: close_sinks
    EditScrawlBloc bloc = BlocProvider.of<EditScrawlBloc>(context);

    return Scaffold(
      backgroundColor: Colors.white30, // for test
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Stack(
                children: <Widget>[
                  _buildScrawlDrawWidget(bloc),
                  _buildPreviewWidget(bloc),
                ],
              ),
            ),
            ScrawlPanelWidget(),
          ],
        ),
      ),
    );
  }

  Widget _buildScrawlDrawWidget(EditScrawlBloc bloc) {
    GlobalKey _scrawlWidgetKey = GlobalKey();
    return GestureZoomBox(
      key: bloc.touchWidgetKey,
      onDown: bloc.drawController.onDown,
      onMove: bloc.drawController.onMove,
      onUp: bloc.drawController.onUp,
      child: Stack(
        key: _scrawlWidgetKey,
        alignment: Alignment.center,
        children: <Widget>[
          Container(
            child: AspectRatio(
              key: bloc.imageWidgetKey,
              aspectRatio: imageAspectRatio,
              child: Image(
                image: bloc.imageProvider,
                fit: BoxFit.fill,
              ),
            ),
          ),
          Positioned.fill(
            child: ScrawlWidget(
              controller: bloc.drawController,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPreviewWidget(EditScrawlBloc bloc) {
    const double PREVIEW_SIZE = 90;
    const double PREVIEW_MARGIN = 16;

    Widget widget;

    widget = Positioned(
      left: PREVIEW_MARGIN,
      top: PREVIEW_MARGIN,
      width: PREVIEW_SIZE,
      height: PREVIEW_SIZE,
      child: ScrawlPreviewWidget(
        controller: bloc.drawController,
      ),
    );

    return widget;
  }
}
